import {
  addOrganization,
  delOrganization,
  exportOrganization,
  getOrgTree,
  getOrganizationByPage,
  updateOrganization,
} from '@/services/system/organization';
import { filterTran, sortTran } from '@/utils/requestUtil';
import { PlusOutlined } from '@ant-design/icons';
import { ModalForm, ProFormText } from '@ant-design/pro-components';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Form, Input, Modal, Tree, message } from 'antd';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';
import styles from './user.less';
const { TreeNode } = Tree;
const { Search } = Input;
const Organization: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [form] = Form.useForm();
  const ref = useRef(null);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([
    '402881e581f6ca830181f6caa70f0003',
    '0-0-1',
  ]);
  const [treeData, setTreeData] = useState([{ title: '组织树', key: '0-0', children: [] }]);
  const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true);
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>(['0-0-0']);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  useEffect(() => {
    // Using an IIFE
    (async () => {
      const result = await getOrgTree();
      setTreeData(result.data);
      setExpandedKeys(['402881e581f6ca830181f6caa70f0003']);
    })();
  }, []);
  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
    },
    {
      title: '组织编码',
      dataIndex: 'orgCode',
    },
    {
      title: '组织名称',
      dataIndex: 'orgName',
    },
    {
      title: '父菜单',
      dataIndex: 'parentId',
    },
    {
      title: '是否启用',
      dataIndex: 'enabled',
    },
    {
      title: '创建日期', //表头显示的名称
      search: false,
      dataIndex: 'createTime',
    },
    {
      title: '创建人', //表头显示的名称
      search: false,
      dataIndex: 'createName',
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      render: (text, record, _, action) => [
        <a
          key="editKey"
          onClick={() => {
            setModalVisit(true);
            setCreateOrUpdate(true);
            setFormTitle('编辑');
            form.setFieldsValue({
              orgCode: record.orgCode,
              orgName: record.orgName,
              parentId: record.parentId,
              enabled: record.enabled,
              id: record.id,
            });
          }}
        >
          编辑
        </a>,
        <a
          key="deleteKey"
          onClick={() => {
            Modal.confirm({
              title: '删除',
              content: '确定要删除吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                await delOrganization({ id: record.id });
                actionRef.current.reload();
              },
            });
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  const onExpand = (expandedKeysValue: React.Key[]) => {
    console.log('onExpand', expandedKeysValue);
    // if not set autoExpandParent to false, if children expanded, parent can not collapse.
    // or, you can remove all expanded children keys.
    setExpandedKeys(expandedKeysValue);
    setAutoExpandParent(true);
  };

  const onCheck = (checkedKeysValue: React.Key[]) => {
    console.log('onCheck', checkedKeysValue);
    setCheckedKeys(checkedKeysValue);
  };
  const onSelect = (selectedKeysValue: React.Key[], info: any) => {
    console.log('onSelect', selectedKeysValue);
    setSelectedKeys(selectedKeysValue);
    actionRef.current.reload();
  };

  const handleSubmit = async (values) => {
    setConfirmLoading(true);
    if (formTitle == '新建') {
      const result = await addOrganization({ ...values, parentId: selectedKeys[0] });
      const result2 = await getOrgTree();
      setTreeData(result2.data);
      if (result != null) {
        message.success('添加成功');
      }
    } else {
      await updateOrganization(values);
    }
    setConfirmLoading(false);
    setModalVisit(false);
    actionRef.current.reload();
  };

  return (
    <div className={styles.father}>
      <div className={styles.left}>
        <Search
          style={{ marginBottom: 8 }}
          placeholder="Search"
          onSearch={(value) => {
            // console.log(value, '---value----');
            // if (value == null || value == '') {
            //   setTreeData(treeAll);
            // } else {
            //   loop(treeAll, value);
            //   console.log(tempArr, '--result-');
            //   setTreeData(tempArr);
            // }
          }}
        />

        <Tree
          onExpand={onExpand}
          expandedKeys={expandedKeys}
          autoExpandParent={autoExpandParent}
          defaultExpandAll
          onSelect={onSelect}
          treeData={treeData}
        />
      </div>
      <div className={styles.right}>
        <ProTable
          headerTitle="组织查询"
          actionRef={actionRef} //用于触发刷新操作等，看api
          revalidateOnFocus={false}
          rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
          formRef={ref}
          size="small"
          scroll={{ x: 'max-content' }}
          toolBarRender={(action, { selectedRows }) => [
            <Button
              key="button"
              icon={<PlusOutlined />}
              onClick={() => {
                setCreateOrUpdate(false);
                setFormTitle('新建');
                form.resetFields();
                setModalVisit(true);
              }}
              type="primary"
            >
              新建
            </Button>,
            <Button
              key="button"
              icon={<PlusOutlined />}
              onClick={() => {
                const filters = filterTran(ref.current.getFieldsValue());
                exportOrganization({
                  current: 1,
                  pageSize: 150000,
                  filters: filters,
                }).then((res) => {
                  const aLink = document.createElement('a');
                  document.body.appendChild(aLink);
                  aLink.style.display = 'none';
                  aLink.href = window.URL.createObjectURL(res);

                  aLink.setAttribute(
                    'download',
                    `Organization_${moment().format('YYYYMMDDHHmm')}.xlsx`,
                  );
                  aLink.click();
                  document.body.removeChild(aLink);
                });
              }}
              type="primary"
            >
              导出
            </Button>,
          ]}
          // tableRender={(_, dom) => (
          //   <div
          //     style={
          //       {
          //         // display: 'flex',
          //         // width: '100%',
          //       }
          //     }
          //   >
          //     <Tree
          //       checkable
          //       onExpand={onExpand}
          //       expandedKeys={expandedKeys}
          //       autoExpandParent={true}
          //       onCheck={onCheck}
          //       checkedKeys={checkedKeys}
          //       onSelect={onSelect}
          //       defaultExpandAll={true}
          //       selectedKeys={selectedKeys}
          //       treeData={treeData}
          //     />
          //     <div
          //       style={
          //         {
          //           // flex: 1,
          //         }
          //       }
          //     >
          //       {dom}
          //     </div>
          //   </div>
          // )}
          request={async (params = {}, sort, filter) => {
            const sorters = sortTran(sort);
            const filters = filterTran(params);
            const result = await getOrganizationByPage({
              ...params,
              sorters: sorters,
              filters: filters,
              parentId: selectedKeys[0],
            });
            return {
              data: result.data.content,
              total: result.data.totalElements,
              success: result.success,
            };
          }}
          columns={columns}
          rowSelection={{}}
        />

        <ModalForm
          visible={modalVisit}
          title={formTitle}
          form={form}
          onFinish={handleSubmit}
          modalProps={{
            destroyOnClose: true,
            onCancel: () => {
              setModalVisit(false);
            },
          }}
        >
          <ProFormText name="id" label="id" placeholder="请输入名称" hidden={true} />
          <ProFormText
            name="orgCode"
            label="组织编码"
            rules={[{ required: true, message: 'Please input your orgCode!' }]}
            disabled={createOrUpdate}
          />
          <ProFormText
            name="orgName"
            label="组织名称"
            rules={[{ required: true, message: 'Please input your orgName!' }]}
            disabled={createOrUpdate}
          />
        </ModalForm>
      </div>
    </div>
  );
};
export default Organization;
